package com.huanzhidadi.springsecurity.expression;

import com.huanzhidadi.springsecurity.model.LoginUser;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;

import java.util.List;

@Component("mySecurityEx")
public class MySecurityExpression {

    /**
     * 实现对xxx:*:*格式的权限进行处理
     * @param authority
     * @return
     */
    public boolean hasPreAuthority(String authority) {
        // 获取当前用户的权限
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        LoginUser loginUser = (LoginUser) authentication.getPrincipal();
        List<String> permissions = loginUser.getPermissions();

        for (String perm : permissions) {
            String[] strings = perm.split(":");
            StringBuffer newPerm = new StringBuffer(strings[0]);
            // 实现对xxx:*:*格式的权限进行处理
            for (int i=1; i<strings.length; i++) {
                if (!"*".equals(strings[i])) {
                    newPerm.append(":").append(strings[i]);
                }
            }
            // 判断用户权限集合中是否存在authority
            if (authority.startsWith(newPerm.toString())) {
                return true;
            }
        }
        return false;
    }
}
